<template>
  <!-- 新增电站 弹窗 -->
  <a-modal
    v-model:open="visible"
    :title="isEdit ? '编辑电站' : '新增电站'"
    @ok="handleOk"
    class="addStation"
    destroyOnClose
    :width="'100vw'"
    @cancel="cancel"
    centered
    :wrapClassName="step === 1 ? 'addStationWrap' : ''"
  >
    <div class="addStationContent">
      <a-steps
        v-if="!isEdit"
        v-model:current="step"
        size="small"
        :items="[
          {
            title: '填写电站基础信息',
            description,
          },
          {
            title: '拓扑图配置',
            description,
          },
          {
            title: '完成',
            description,
          },
        ]"
      />

      <!-- 电站基础信息 表单 -->
      <Form
        ref="addStationFormRef"
        v-if="step === 0"
        :rowData="rowData"
        :isEdit="isEdit"
        @validateFormPass="validateFormPass"
      />

      <!-- 拓扑图拖拽组件 -->
      <a-spin tip="保存中..." :spinning="dragLoading">
        <DragConfig
          ref="dragConfig"
          v-if="step === 1"
          :rowData="rowData"
          :addStationId="addStationId"
          :topologyMap="topologyMap"
          @getElements="getElements"
          @handleSaveConfig="handleSaveConfig"
        />
      </a-spin>
    </div>
    <template #footer>
      <div
        v-if="!isEdit"
        :class="['footerBar', step === 1 ? 'fixPosition' : '']"
      >
        <div v-if="step === 0">
          <!-- <a-button @click="handleCancel">暂存</a-button> -->
          <a-button type="primary" :loading="loading" @click="handleNext"
            >下一步</a-button
          >
        </div>
        <div v-if="step === 1">
          <a-button @click="handleSubmit" type="primary">保存</a-button>
        </div>
      </div>
      <div v-else :class="['footerBar', step === 1 ? 'fixPosition' : '']">
        <a-button
          v-if="!isEditDrag && step === 1"
          type="primary"
          @click="handleIsEditDrag"
          v-hasPermission="'equipAccessTopologyEdit'"
          >编辑</a-button
        >
        <div v-else>
          <!-- <a-button @click="cancel">取消</a-button> -->
          <a-button
            type="primary"
            :loading="loading"
            @click="step === 0 ? handleFormSubmit() : handleSubmit()"
            >保存</a-button
          >
        </div>
      </div>
    </template>
  </a-modal>
</template>
<script setup>
// 
import Form from "./Form/index.vue"
import DragConfig from "./DragConfig/index.vue"

import { useStionConfigStore } from "@/stores/stationConfig"
import { EQUIP_TYPE } from "@/constants/stationConfig"
import { pickBy } from "lodash-es"
const { stionConfigState, changeDragData, changeIsEditDrag } =
  useStionConfigStore()
const isEditDrag = computed(() => stionConfigState.isEditDrag)
const $api = inject("$api")
const props = defineProps({
  addStationVisible: {
    type: Boolean,
    default: false,
  },
  rowData: {
    type: Object,
  },
  isEdit: {
    type: Boolean,
    default: false,
  },
})
const emits = defineEmits([
  "update:addStationVisible",
  "getCompanyStationtPage",
])
const visible = ref(props.addStationVisible)
const step = ref(0)
const addStationFormRef = ref(null)
const stationId = ref(null)
const isChargeProject = computed(() => props.rowData.isChargeProject)
const isContainerProject = computed(() => props.rowData.isContainer)
watch(
  () => props.addStationVisible,
  (val) => {
    visible.value = val
  }
)
const dragLoading = ref(false)
const handleNext = async () => {
  await addStationFormRef.value.validateForm()
}
const loading = ref(false)
const addStationId = ref(null) // 新增电站信息后该条数据id
const validateFormPass = async (data) => {
  // 提交 电站基础信息 表单
  const { isMultiple, operationDate, ...rest } = data
  const params = {
    ...rest,
    operationDate: operationDate + " 00:00:00",
    oldSysStationIds: data?.oldSysStationIds
      ? data?.oldSysStationIds.join(",")
      : "",
  }
  if (props.isEdit) {
    // 编辑带上id
    params.id = props.rowData.id
  }

  // 提交逻辑
  loading.value = true
  const res = await $api.companyStation(params, props.isEdit ? "put" : "post")
  loading.value = false
  if (res.code === 0) {
    message.success(props.isEdit ? "编辑成功" : "新增成功")
    if (!props.isEdit) {
      addStationId.value = res.data
      changeIsEditDrag(true)
      emits("getCompanyStationtPage", data)
    }
    if (props.isEdit) {
      // 如果是编辑表单，直接关闭弹窗
      changeIsEditDrag(true)
      emits("getCompanyStationtPage", data)
      cancel()
    } else {
      // 如果是新增表单，跳到下一步
      changeIsEditDrag(true)
      emits("getCompanyStationtPage", data)
      step.value = 1
      stationId.value = res.data // 新增电站信息后该条数据id，用于后续拓扑图保存的入参
    }
    // changeIsEditDrag(true)
    // emits("getCompanyStationtPage", data)
  }
}
const elements = ref([])
const getElements = async (data) => {
  elements.value = data
  await nextTick()
  // validateDragPass();
}
const handleSaveConfig = async (data) => {
  await nextTick()
  validateDragPass()
}
const validateDragPass = async () => {
  const data = elements.value
  if (data.length === 0) {
    return message.error("拓扑图无更新或为空")
  }
  let prefixBackendData = []
  for (const item of elements.value) {
    prefixBackendData.push({
      systemId: item.systemId,
      systemType: item.systemType,
      parentId: item.parentId,
    })
  }
  prefixBackendData = prefixBackendData.filter((item) => item.systemId)
  const params = {
    stationId: props.rowData.stationId,
    backendData: JSON.stringify(prefixBackendData),
    frontData: JSON.stringify({
      data,
    }),
  }
  params.stationId = props.rowData.stationId || stationId.value // 编辑时直接用page返回的电站id
  dragLoading.value = true
  let apiName = ''
  if (isChargeProject.value) {
    // 储充项目
    apiName = 'chargingStationTopologyMap'
  } else if (isContainerProject.value) {
    // 集装箱项目
    apiName = 'containerStationTopologyMap'
  } else {
    // 其他项目
    apiName = 'stationTopologyMap'
  }
  const res = await $api[apiName](params, "post")
  dragLoading.value = false
  if (res && res.code === 0) {
    message.success("保存拓扑图成功")
    changeIsEditDrag(false)
  }
}
const changeSetp = (stepNum) => {
  step.value = stepNum
}
const cancel = () => {
  emits("update:addStationVisible", false)
  step.value = 0
  topologyMap.value = []
  addStationFormRef.value?.cancel()
  changeDragData({})
}
const topologyMap = ref([]) // 拓扑图前端回显数据
const getStationTopologyMapDetails = async (stationId) => {
  // 查询拓扑图
  const res = await $api.stationTopologyMapDetails(stationId)
  if (res && res.code === 0) {
    topologyMap.value = res?.data?.topologyMap || []
  }
}
const handleFormSubmit = async () => {
  await addStationFormRef.value.validateForm()
}
const handleSubmit = () => {
  validateDragPass()
}
const handleIsEditDrag = () => {
  changeIsEditDrag(true)
}
onMounted(() => {})

defineExpose({ changeSetp, getStationTopologyMapDetails })
</script>
<style lang="less" scoped>
.addStationContent {
  padding: 10px 15px;
}
.footerBar {
  text-align: center;
}
.ant-steps {
  pointer-events: none;
}
</style>
<style lang="less">
.addStationWrap {
  // width: 100vw !important;
  // max-width: 100vw !important;
  // height: 100vh !important;
  // top:0;
  // padding-bottom:0;
  .ant-modal-footer {
    position: sticky;
    bottom: 10px;
    width: 300px;
    left: 50%;
    transform: translateX(-50%);
  }
  // .canvasOutContent {
  //   width: calc(100vw - 200px)
  // }
}
</style>
